import { good_fav, good_unfav, good_favlist, shopcart_list,
    shopcart_clear,
    shopcart_add,
    shopcart_sub} from '../utils/api'


function create_cancel_collect(params) {
    return { type: "CANCEL_COLLECT", params }
}
function create_collect_action(params) {
    return { type: "COLLECT", params }
}
// 收藏列表
// 创建同步action，'COLLECT_LIST'
function create_collectlist_action(params) {
    return { type: 'COLLECT_LIST', params }
}

// 添加到购物车
function shoppcar_add(params){
    return { type: "SHOPPCAT_ADD",params }
}

//购物车列表
function shopcar_list(params){
    return { type:"SHOPPCAT_LIST",params}
}





function request_collect_action(params) {
    return function (dispatch) {
        //发请求
        var userinfo = localStorage.getItem('userinfo') ? JSON.parse(localStorage.getItem('userinfo')) : {};
        good_fav({ goodid: params.id, userid: userinfo.id }).then((res) => {
            if (res.data.code === 200) {
                //触发一个同步action
                dispatch(create_collect_action(params))
            }
        })
    }
}
function request_cancel_collect(params) {
    return function (dispatch) {
        //发请求
        var userinfo = localStorage.getItem('userinfo') ? JSON.parse(localStorage.getItem('userinfo')) : {};
        good_unfav({ goodid: params.id, userid: userinfo.id }).then((res) => {
            if (res.data.code === 200) {
                //触发一个同步action
                dispatch(create_cancel_collect(params))
            }
        })
    }
}

// 创建异步action
function request_cancellist_collect(params) {
    return function (dispatch) {
        var userinfo = localStorage.getItem('uerinfo') ? JSON.parse(localStorage.getItem('userinfo')) : {};
        // 发收藏列表的请求
        good_favlist({ userid: userinfo.id }).then((res)=>{
            if(res.data.code===200){
                dispatch( create_collectlist_action(res.data.good_favlist) )
            }
        })
    }
}

//添加到购物
function request_shoppcart_add(params){
    return function (dispatch){
        var userinfo=localStorage.getItem("userinfo")?JSON.parse(localStorage.getItem('userinfo')) : {};
        shopcart_add({userid:userinfo.id,goodid:params.id}).then((res)=>{
            if(res.data.code===200){
                dispatch(shoppcar_add(params))
            }
        })
    }
}

function request_shoppcart_list(params){
    return function(dispatch){
        var userinfo=localStorage.getItem("userinfo")?JSON.parse(localStorage.getItem('userinfo')) : {};
        shopcart_list({userid:userinfo.id}).then((res)=>{
            if(res.data.code===200){
                dispatch(shopcar_list(res.data.list))
            }
        })
    }
}





export {
    // create_cancel_collect,
    request_collect_action,
    // create_collect_action
    request_cancel_collect,
    request_cancellist_collect,
    request_shoppcart_add,
    request_shoppcart_list
}